package com.gyg.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * ThreadPoolExecutor线程配置类
 */
@Slf4j
@EnableAsync
@Configuration
public class ThreadPoolConfig {
    /**
     * 核心线程数
     */
    private final int CORE_POOL_SIZE = 5;
    /**
     * 最大线程数
     */
    private final int MAX_POOL_SIZE = 10;
    /**
     * 保持连接时间
     */
    private final long KEEP_ALIVE_TIME = 1;
    /**
     * 队列长度
     */
    private final int QUEUE_CAPACITY = 100;
    /**
     * 时间单位
     */
    private final TimeUnit TIME_UNIT = TimeUnit.SECONDS;

    private ThreadPoolExecutor threadPoolExecutor;

    @Bean("myThreadPool01")
    public ThreadPoolExecutor createThreadPoolExecutor() {
        //利用guava：创建一个线程工程，用于线程池命名
        ThreadFactory threadFactory = new ThreadFactoryBuilder()
                .setNameFormat("MyThreadPool" + "-%d")
                .setDaemon(true).build();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TIME_UNIT,
                new ArrayBlockingQueue<>(QUEUE_CAPACITY),
                threadFactory,
                new ThreadPoolExecutor.CallerRunsPolicy());
        this.threadPoolExecutor = threadPoolExecutor;
        return this.threadPoolExecutor;
    }

    public ThreadPoolExecutor getThreadPool() {
        return this.threadPoolExecutor;
    }
}
